package top.hekun.study.tree;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.CheckClassAdapter;
import top.hekun.study.core.util.ClassFileUtil;
import top.hekun.study.tree.visitor.simple.MyClassVisitor1;

import java.io.File;

/**
 * 使用tree 简单修改文件
 */
public class TreeClassSimpleModifyClassDemo {

    public static void main(String[] args) {
        byte[] classBytes = ClassFileUtil.getClassFileByteToClassName("HelloWord");
        ClassReader classReader = new ClassReader(classBytes);

        ClassVisitor classVisitor;
        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        classVisitor = classWriter;


        classVisitor = new CheckClassAdapter(classVisitor);
        // 类编写器
        int apiVersion = Opcodes.ASM9;

        // 更改类的版本
        classVisitor = new MyClassVisitor1(apiVersion, classVisitor);

        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES | ClassReader.SKIP_DEBUG);
        byte[] classByte = classWriter.toByteArray();

        writeClassFileCore(classByte, getClassFile());

    }

    private static File getClassFile() {
        String className = "HelloWordTreeModifyClass";
        File file = new File(ClassFileUtil.getClassFileModelPath(), className + ".class");
        return file;
    }

    private static void writeClassFileCore(byte[] core, File classFilePath) {
        ClassFileUtil.classFileCoreWrite(core, classFilePath);
    }
}
